import React, { useContext, useEffect } from 'react';
import { useCallback } from 'react';
import { Navigate, useLocation, useRoutes } from 'react-router-dom';
import { useModel } from 'foca';
import { useWindowScroll } from '@mantine/hooks';

import { userModel } from '@/models';

import { routes } from './routes';
import type { IRoute } from './types';

const Routing: React.FC = () => {
	const { isLogin } = useModel(userModel);
	const { pathname } = useLocation();
	const [scroll, scrollTo] = useWindowScroll();
	useEffect(() => {
		scrollTo({ y: 0 });
	}, [pathname, scrollTo]);
	const renderRoutes = useCallback(
		(_routes: IRoute[]) => {
			return _routes.map(route => {
				const { auth, redirect, children } = route;
				// 深拷贝避免原始配置被篡改
				const newRoute = Object.assign({}, route);

				if (children) newRoute.children = renderRoutes(children);

				if (redirect) newRoute.element = <Navigate to={redirect} />;
				if (auth && !isLogin) {
					// setSignInPopupVisible(true)
				}
				// if (auth && !isLogin) newRoute.element = <Navigate to='/sign' replace />
				if (auth && !isLogin) {
					newRoute.element = <Navigate to="/" replace />;
				}
				return newRoute;
			});
		},
		[isLogin]
	);

	return useRoutes(renderRoutes(routes));
};

export default Routing;
